<template>
  <header>
    <div @click="goBack">
      <i><img src="@/assets/images/icons/fanhui.png"></i>
    </div>
    <slot>
      <form onsubmit="return false" action="" class="search-input" @keyup.enter="goSearchList">
        <input type="search" placeholder="搜索商品名称" v-model="inputValue"></input>
      </form>
    </slot>
    <div @click="goSearchList">
      <i><img src="@/assets/images/icons/fangdajing.png"></i>
    </div>
  </header>
</template>

<script>
export default {
  name: "Header",
  props:{
    queryKey:String
  },
  data(){
    return{
      inputValue:this.queryKey,
      searchArr:[],
    }
  },
  created() {
    if(this.$route.query) {
      this.key = this.$route.query.key;
    }
  },
  methods:{
    goBack(){ //返回
      this.$router.back()
    },
    goSearchList(){

      if(this.$route.path == '/classification'||this.$route.path == '/cart'){
        //跳转页面
        this.$router.push({
          path:'/search-list'
        })
      }

      //输入为空，直接返回，不搜索
      if(!this.inputValue) {
        return;
      }

      //判断之前有没有本地存储
      if(!localStorage.getItem('searchList')){    //没有
        localStorage.setItem('searchList', '[]')
      }else{    //之前有
        this.searchArr = JSON.parse(localStorage.getItem('searchList'))
      }

      //增加数据
      this.searchArr.unshift(this.inputValue)

      //ES6去重，这里是对象，还需转化为数组
      let obj = new Set(this.searchArr)

      //给本地存储赋值
      localStorage.setItem('searchList',JSON.stringify(Array.from(obj)))

      //跳转页面
      this.$router.push({
        path:'/search-list',
        query:{
          key: this.inputValue
        }
      })
      this.inputValue = ''

    }
  }
}
</script>

<style scoped lang="scss">
header{
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #F7F7F7;
  height: 48px;
  img{
    width: 24px;
    height: 24px;
  }
  .search-input{
    width: 80%;
    height: 60%;
    background-color: #FFFFFF;
    input{
      width: 100%;
    }
  }
}
</style>